﻿/* 
©2006 Rodrigo Diniz 
www.rodrigodiniz.qsh.eu 
You may use this code in anyway you like but do not remove this copyright 
*/
//Filter Helper
Ext.grid.Grid.prototype.filter=function(filterCol,filterValue){
    this.clearSelection();
    this.filterCol=filterCol;
    this.filterValue=filterValue;
    var lastO= this.dataSource.lastOptions;
    this.dataSource.load({params:{start:0, limit:lastO.limit,'filtercol': filterCol,'filterValue':filterValue}});
  
}
/*
Helper gets the data in the selected row as an object
with properties names that match the FIELDS
*/
Ext.grid.Grid.prototype.getRowData=function(){
    var dm = this.dataSource;
    var rowSel=this.selModel.getSelected();
    var objRet =new Object();
    for(var i=0;i< dm.fields.getCount();i++){
            objRet[dm.fields.get(i).name]=rowSel.data[dm.fields.get(i).name];
    }
   
    return objRet;
}
Ext.grid.Grid.prototype.getAllRows=function(){
  var objArray= new Array();
  var dm=this.dataSource;
  var len= dm.getCount();
  var fields=dm.schema.fields
    for(var i = 0; i < len; i++){
        var node= dm.getNode(i);
        objRet= new Object();
        for(var j=0;j< fields.length;j++){
          objRet[fields[j]]=dm.getNamedValue(node,fields[j]);
        }
        objArray.push(objRet);
    } 
  return objArray;
}
//helper --lets the grid know that no row is selected
Ext.grid.Grid.prototype.clearSelection=function(){
    this.selModel.clearSelections();
};
/*
    NumberPagedToolbar 
    Extends Toolbar
       
*/
Ext.NumberPagingToolbar=function(el,ds,config){
  
    Ext.NumberPagingToolbar.superclass.constructor.call(this, el, null, config);
    this.ds = ds;
    this.cursor = 0;
    ds.on("load", this.onLoad, this);
    this.el=el;
}
Ext.NumberPagingToolbar=function(el,ds,config){
  
    Ext.NumberPagingToolbar.superclass.constructor.call(this, el, null, config);
    this.ds = ds;
    this.cursor = 0;
    ds.on("load", this.onLoad, this);
    this.el=el;
}
Ext.extend(Ext.NumberPagingToolbar, Ext.Toolbar, {
//build the pager 
 onLoad : function(ds, r, o){
        
        this.cursor = o.params ? o.params.start : 0;
        this.sort=o.params.sort? o.params.sort:'';
        this.dir= o.params.dir?o.params.dir:'';
        var elFooter=YAHOO.util.Dom.getElementsByClassName("x-toolbar");
        var dh = Ext.DomHelper;
        elFooter=elFooter[elFooter.length-1];
        elFooter.innerHTML="";
       
        var d = this.getPageData();
        var currentPage= d.activePage+1;
        var numberOfPages=d.pages;
        if(numberOfPages ==1){
            elFooter.innerHTML="";
            return;
        }
        var start= currentPage;
        if(currentPage<=5)
        {
            start=1;
        }
        else
        {
            for(var j=start-1;j> start-6;j--)
            {
	            if(j%5==0)
	            {
		            start=j;
		            break;
	            }
            }
        }
        tpl = new Ext.DomHelper.Template("<span class='pagination'> <ul>");
        var elPrin=tpl.append(elFooter);
        var i;
        for (i = start; i <= numberOfPages; i++)
        {
          
            if(i==start +6 ||(start==1&& i==6) )
            {
                el= dh.append(elPrin, {tag:'li',html:'&nbsp;',
                    children:[{tag:'a' ,href:'#',html:'...'}]                
                }, true);
                el.on("click",this.onClick.createDelegate(this, [i-1]));
	           
	            break;
            }
            if(currentPage > 5 && i==start)
            {
	            el= dh.append(elPrin, {tag:'li',html:'&nbsp;',
                    children:[{tag:'a' ,href:'#',html:'...'}]                
                }, true);
                el.on("click",this.onClick.createDelegate(this, [start-1]));
	            continue;
            }
            if (i != currentPage)
            {
                el= dh.append(elPrin, {tag:'li',html:'&nbsp;',
                    children:[{tag:'a' ,href:'#',html:i}]                
                }, true);
                el.on("click",this.onClick.createDelegate(this, [i-1]));
	            
            }
            else
            {
                el= dh.append(elPrin, {tag:'li',html:i+'&nbsp;',cls:'currentpage'  }, true);
	            
            }
    		
        }  
        
       
       },
        //called on the page number click
        onClick:function(pageNum){
             var ds = this.ds;
             ds.load({params:{start: pageNum, limit: this.pageSize,sort:this.sort,dir:this.dir,sort:this.sort}});
        }
      ,
      getPageData : function(){
        var total = this.ds.getTotalCount();
        return {
            total : total,
            activePage : this.cursor,
            pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
        };
    }
   }
);


/*
 * 
 * Copyright(c) 2006-2007, Rodrigo Diniz
 * 
 * http://www.rodrigodiniz.qsh.eu
 * 
 */
Ext.data.WebserviceProxy = function(conn){
    
    Ext.data.WebserviceProxy.superclass.constructor.call(this);
    //this.conn = conn.events ? conn : new Ext.data.Connection(conn);
    Ext.apply(this,conn);
};

Ext.extend(Ext.data.WebserviceProxy, Ext.data.DataProxy, {
    getConnection : function(){
        return this.conn;;
    },
    
   load : function(params, reader, callback, scope, arg){
        //user context object to pass the parameters to response
        var userContext={callback:callback,reader:reader,arg:arg,scope:scope}
        Sys.Net.WebServiceProxy.invoke(this._WebservicePath, this._WebServiceMethod, false,params,Function.createDelegate(this, this.loadResponse), Function.createDelegate(this, this.loadResponse),userContext);

    },
 
     loadResponse : function(response,userContext){
      
        if(response._message){
            this.fireEvent("loadexception", response._message);
            userContext.callback.call(userContext.scope, null,userContext.arg, false);
            return;
        }
      
        var result;
        try {
            result = userContext.reader.read(response);
        }catch(e){
            this.fireEvent("loadexception",e);
            userContext.callback.call(userContext.scope, null,userContext.arg, false);
            return;
        }
        
        //call loadRecords
         userContext.callback.call(userContext.scope, result, userContext.arg, true);
    },
    
    update : function(dataSet){
        
    },
    
    updateResponse : function(dataSet){
        
    }
});
/*
 * DataSetReader Reader
 * Copyright(c) 2007, Rodrigo Diniz.
 * 
 * 
 */

Ext.data.DataSetReader= function(meta, recordType){
    Ext.data.DataSetReader.superclass.constructor.call(this, meta, recordType);
};
Ext.extend(Ext.data.DataSetReader, Ext.data.DataReader, {
    read : function(response){
      
        var doc = response.childNodes[response.childNodes.length-1]
        doc=doc.childNodes[doc.childNodes.length-1];
        if(!doc) {
            throw {message: "XmlReader.read: XML Document not available"};
        }
        return this.readRecords(doc);
    },
    
    readRecords : function(doc){
       
        this.xmlData = doc;
        var root = doc.documentElement || doc;
    	var q = Ext.DomQuery;
    	var recordType = this.recordType, fields = recordType.prototype.fields;
    	var sid = this.meta.id;
    	var totalRecords = 0;
        var records = [];
    
    	if(!this.meta.record){
    	    this.meta.record="Table";
    	}
    	var ns = q.select(this.meta.record,root);
        for(var i = 0, len = ns.length; i < len; i++) {
	        var n = ns[i];
	        var values = {};
	        var id = sid ? q.selectValue(sid, n) : undefined;
	        for(var j = 0, jlen = fields.length; j < jlen; j++){
	            var f = fields.items[j];
                var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
	            v = f.convert(v);
	            values[f.name] = v;
	        }
	        var record = new recordType(values, id);
	        record.node = n;
	        records[records.length] = record;
	    }
	    if(!this.meta.totalTable){
	        this.meta.totalTable="Table1";
	    }
	    var ns = q.select(this.meta.totalTable,root);
	    var n = ns[0];
	    if(this.meta.totalRecords){
	        totalRecords=q.selectValue(this.meta.totalRecords, n);
	    }
	    
	    return {
	        records : records,
	        totalRecords : totalRecords || records.length
	    };
    }
});
/*
* Some overrides to make the PagingToolbar
* always send sort and sortdir
*/
Ext.apply(Ext.PagingToolbar.prototype,{
    onLoad : function(ds, r, o){
       this.cursor = o.params ? o.params.start : 0;
       var d = this.getPageData(), ap = d.activePage, ps = d.pages;
       this.params=o.params;
       this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
       this.field.dom.value = ap;
       this.first.setDisabled(ap == 1);
       this.prev.setDisabled(ap == 1);
       this.next.setDisabled(ap == ps);
       this.last.setDisabled(ap == ps);
       this.loading.enable();
       this.updateInfo();
    },
    onClick : function(which){
        var ds = this.ds;
        switch(which){
            case "first":
                ds.load({params:{start: 0, limit: this.pageSize,sort:this.params.sort,dir:this.params.dir}});
            break;
            case "prev":
                ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize,sort:this.params.sort,dir:this.params.dir}});
            break;
            case "next":
                ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize,sort:this.params.sort,dir:this.params.dir}});
            break;
            case "last":
                var total = ds.getTotalCount();
                var extra = total % this.pageSize;
                var lastStart = extra ? (total - extra) : total-this.pageSize;
                ds.load({params:{start: lastStart, limit: this.pageSize,sort:this.params.sort,dir:this.params.dir}});
            break;
            case "refresh":
                ds.load({params:{start: this.cursor, limit: this.pageSize,sort:this.params.sort,dir:this.params.dir}});
            break;
        }
     }   
   }
 )
// Ext.PagingToolbar.prototype.onClick = function(which){
//        var ds = this.ds;
//        switch(which){
//            case "first":
//                ds.load({params:{start: 0, limit: this.pageSize}});
//            break;
//            case "prev":
//                ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
//            break;
//            case "next":
//                ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
//            break;
//            case "last":
//                var total = ds.getTotalCount();
//                var extra = total % this.pageSize;
//                var lastStart = extra ? (total - extra) : total-this.pageSize;
//                ds.load({params:{start: lastStart, limit: this.pageSize}});
//            break;
//            case "refresh":
//                ds.load({params:{start: this.cursor, limit: this.pageSize}});
//            break;
//        }
//}